package kotlincode.suspendkthttp18

import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import java.lang.reflect.Type

/**
 * 作用是承载[MyCallBack]，或者说，它是用来调用[MyCallBack]的
 *
 * @param call OkHttp的Call对象
 * @param gson JSON解析的Gson对象
 * @param type 反射类型Type
 *
 * @author weilinliang
 * @since 2022/8/26
 */
class MyCall<T>(
    private val call: Call,
    private val gson: Gson,
    private val type: Type
) {
    fun call(callBack: MyCallBack<T>): Call {
        // 步骤1， 使用call请求API
        // 步骤2， 根据请求结果，调用callback.onSuccess()或者是callback.onFail()
        // 步骤3， 返回OkHttp的Call对象
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callBack.onFail(e)
            }

            override fun onResponse(call: Call, response: Response) {
                try {
                    val resultBody = gson.fromJson<T>(response.body?.string(), type)
                    callBack.onSuccess(resultBody)
                } catch (e: Exception) {
                    callBack.onFail(e)
                }
            }
        })
        return call
    }
}